import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { invoke } from '@tauri-apps/api/core'

// 定义路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/yukoume'
  },
  {
    path: '/yukoume',
    name: 'Yukoume',
    component: () => import('../components/pages/YukoumePage.vue')
  },
  {
    path: '/fishing-circle',
    name: 'FishingCircle',
    component: () => import('../components/pages/FishingCirclePage.vue')
  },
  {
    path: '/circle-detail/:id',
    name: 'CircleDetail',
    component: () => import('../components/pages/circle/CircleDetail.vue'),
    props: true
  },
  {
    path: '/circle-edit/:id',
    name: 'CircleEdit',
    component: () => import('../components/pages/circle/FishingCircleEditor.vue'),
    props: true
  },
  {
    path: '/fishing-spots',
    name: 'FishingSpots',
    component: () => import('../components/pages/FishingSpotsPage.vue')
  },
  {
    path: '/add-spot',
    name: 'AddSpot',
    component: () => import('../components/pages/AddSpotPage.vue')
  },
  {
    path: '/spot-detail/:id',
    name: 'SpotDetail',
    component: () => import('../components/pages/SpotDetailPage.vue'),
    props: true
  },
  {
    path: '/user-management',
    name: 'UserManagement',
    component: () => import('../components/pages/UserManagementPage.vue')
  },
  {
    path: '/reports',
    name: 'Reports',
    component: () => import('../components/pages/ReportsPage.vue')
  },
  {
    path: '/setting',
    name: 'Setting',
    component: () => import('../components/pages/SettingPage.vue')
  },
  {
    path: '/favorites',
    name: 'Favorites',
    component: () => import('../components/pages/FavoritesPage.vue')
  },
  {
    path: '/visits',
    name: 'Visits',
    component: () => import('../components/pages/VisitsPage.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

import { useAuth } from '../composables/useAuth'

// Get auth instance (we need a non-reactive version for router)
let authInstance = null
function getAuth() {
  if (!authInstance) {
    authInstance = useAuth()
  }
  return authInstance
}

// Authentication guard
router.beforeEach(async (to, from, next) => {
  // Skip auth check for root path (login page)
  if (to.path === '/') {
    next()
    return
  }

  try {
    const auth = getAuth()
    // First check local state
    if (auth.isLoggedIn.value) {
      next()
      return
    }
    
    // Only check backend if local state shows not logged in
    // This prevents constant queries to the backend
    const isLoggedIn = await invoke<boolean>('is_user_logged_in')
    
    if (isLoggedIn) {
      next()
    } else {
      // Redirect to login page
      next('/')
    }
  } catch (error) {
    console.error('Auth check failed:', error)
    // On error, redirect to login
    next('/')
  }
})

export default router